package com.polaris.live.ui.message.fragment

import android.os.Bundle
import android.util.LayoutDirection
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.cacha.DisplayUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.databinding.FragmentHomeMainMessageBinding
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.interfaces.OnGotoListener
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.message.HomeMianMessageViewModel
import com.polaris.live.widget.tab.OnTabSelectListener
import com.polaris.live.widget.tab.TabBean

/**
 * HomeMainMessageFragment
 *
 * @author Created by 半仙 on 2024/6/27/027 9:32
 */
class HomeMainMessageFragment : BaseVbFragment<HomeMianMessageViewModel, FragmentHomeMainMessageBinding>(),
    OnAutoRefreshListener,
    OnGotoListener {

    private val mFragments = ArrayList<Fragment>()

    private val mTitles = ArrayList<TabBean>()

    private var mTabAdapter: ViewPagerAdapter? = null

    private var mLastRequestAgencyUserList = 0L

    private var mIsShowIvHi = false

    private val mMainFamilyFragment by lazy {
        MainFamilyFragment().apply {
            setTotalBack {
                setTotal(it)
            }
        }
    }

    private fun setTotal(total: Long) {
        mBinding.peopleCountTv.text = "$total"
    }

    override fun initView(savedInstanceState: Bundle?) {
        updateImmersionBar()
        initTitle()
        val user = UserManager.getUser()
        mIsShowIvHi =
            user.profile?.agencyId != null && !CommonUtils.isMan(UserManager.getUser().sex) && user.coverPhoto?.validCover == true

        if (resources.configuration.layoutDirection == LayoutDirection.RTL) {
            mBinding.totalLl.setBackgroundResource(R.drawable.r24_back_000000_trbr_5)
        }

        mBinding.ivHi.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.MESSAGE_GREET_ACTIVITY)
                .navigation(requireActivity())
        }

        mViewModel.mAgencyLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.list.isNotEmpty()) {
                    val myFragments: List<MainFamilyFragment> = mFragments.filterIsInstance<MainFamilyFragment>()
                    if (UserManager.getUser().profile?.ownerAgencyId != null && myFragments.isNullOrEmpty()) {
                        mTitles.add(TabBean(StringUtils.getString(string.family)))
                        mFragments.add(mMainFamilyFragment)

                        mTabAdapter?.setFragments(mFragments)
                        mBinding.pager.offscreenPageLimit = mFragments.size
                        mBinding.tab.setTabs(mTitles, mBinding.svScroll)
                    }
                }
            })
        }
    }

    private fun initTitle() {
        val page = DisplayUtil.getSecondaryPagesByPrimaryPage(DisplayUtil.MESSAGE)
        page?.secondaryPages?.forEach {
            when (it) {
                DisplayUtil.MESSAGE_MESSAGE -> {
                    mTitles.add(TabBean(StringUtils.getString(string.message)))
                    mFragments.add(MainMessageFragment())
                }

                DisplayUtil.MESSAGE_FAMILY -> {
                    mTitles.add(TabBean(StringUtils.getString(string.family)))
                    mFragments.add(mMainFamilyFragment)
                }
            }
        }

        mBinding.tab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                mBinding.pager.currentItem = position
                onAutoRefresh()
            }

            override fun onTabReselect(position: Int) {

            }
        })
        mBinding.pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                onAutoRefresh()
                val fragment = mFragments.getOrNull(position)
                if (fragment is MainMessageFragment) {
                    if (mIsShowIvHi) {
                        mBinding.ivHi.visibility = View.VISIBLE
                    }
                    mBinding.totalLl.visibility = View.GONE
                } else if (fragment is MainFamilyFragment) {
                    mBinding.totalLl.visibility = View.VISIBLE
                    mBinding.ivHi.visibility = View.GONE
                }

            }
        })



        mTabAdapter = ViewPagerAdapter(mFragments, this)
        mBinding.pager.adapter = mTabAdapter
        mBinding.pager.offscreenPageLimit = mFragments.size
        mBinding.tab.setViewPage(mBinding.pager)
        mBinding.tab.setTabs(mTitles, mBinding.svScroll)

        DisplayUtil.getDefaultIndexBySecondaryPrimaryId(
            getGotoDate()?.index,
            DisplayUtil.MESSAGE,
            page
        )?.also {
            mBinding.tab.onPageSelected(it)
            mBinding.pager.setCurrentItem(it, false)
        }
    }

    private var mGotoData: OnGotoListener.GotoData? = null

    override fun onGoto(gotoData: OnGotoListener.GotoData) {
        if (!isCreated()) {
            mGotoData = gotoData
        } else {
            mBinding.pager.currentItem = gotoData.index
        }
    }

    private fun getGotoDate(): OnGotoListener.GotoData? {
        return if (mGotoData == null) {
            null
        } else {
            mGotoData.apply {
                mGotoData = null
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (isCreated()) {
            mFragments.getOrNull(mBinding.pager.currentItem)?.onHiddenChanged(hidden)
            if (!hidden && UserManager.getUser().profile?.ownerAgencyId != null) { //是公会长并且显示时在没有家族列表  每60秒拉取一次
                val time = System.currentTimeMillis()
                val myFragments = mFragments.filterIsInstance<MainFamilyFragment>()
                if (time - mLastRequestAgencyUserList > 60 * 1000 && myFragments.isEmpty()) {
                    mLastRequestAgencyUserList = time
                    mViewModel.getAgencyUserList()
                }
            }
        }
    }

    override fun onAutoRefresh() {
        if (!isCreated()) {
            return
        }
        val fragment = mFragments[mBinding.pager.currentItem]
        if (fragment is OnAutoRefreshListener) {
            (fragment as OnAutoRefreshListener).onAutoRefresh()
        }
    }

    private fun updateImmersionBar() {
        NavigationBarUtils.setImmersionBarForMain(this, mBinding.consTab)
    }

}